soj 1152,1153 马的周游问题

附录:代码

#include<iostream>
#include<cstdlib>
#include<cstdio>
#include<memory.h>
#include<vector>
#include<algorithm>

using namespace std;

typedef struct posi
{
   int x;
   int y;
   int selection;
   posi(){};
   posi(int a,int b){x=a,y=b,selection=0;}
}pos;

bool visit[9][9];

int dir_x[] = {-1, -1, -2, -2, 1, 1, 2, 2};
int dir_y[] = {-2, 2, 1, -1, 2, -2, 1, -1};

int path[64];

bool isValid(pos p)
{
      if( p.x<0 || p.x>7 || p.y<0 || p.y>7 || visit[p.x][p.y]==1)
       return false;
     return true;
}

bool cmp(pos a,pos b)
{
    return (a.selection<b.selection);
}
bool dfs(pos now,int step)
{
    int i,j;
    pos p(0,0);
    if( step==64){
        for(i=0; i<63; i++)
         cout<<path[i]<<" ";
         cout<<path[63]<<endl;
        return true;
    }
        vector<pos> temp;
             for(i=0; i<8; i++)
              {
                   p.x=(now.x)+dir_x[i];
                   p.y=(now.y)+dir_y[i];
                    p.selection=0;
                    if(isValid(p))
                    {
                        pos k;
                        for(  j=0; j<8; j++)
                        {
                            k.x=(p.x)+dir_x[j];
                            k.y=(p.y)+dir_y[j];
                            if( isValid(k))
                            p.selection++;
                        }
                        temp.push_back(p);
                    }

              }
              sort(temp.begin(),temp.end(),cmp);
              for( i=0; i<temp.size(); i++){
                      p=temp[i];
                      visit[p.x][p.y]=1;
                      path[step]=p.x*8+p.y+1;
                      if(dfs( p,step+1))
                         return true;

                     visit[p.x][p.y]=0;
            }

    return false;
}


int main()
{
    int start,row,col;
    while(cin>>start && start!=-1)
    {
        memset(visit,0,sizeof(visit));

        row=(start-1)/8;
        col=(start-1)%8;

       visit[row][col]=1;
       path[0]=start;
        dfs(pos(row,col),1);


    }
    return 0;
}


        

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值